package test.classLoader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author yachao.Guo
 * @version 1.0.0  2019-04-12
 */
public class ClassIsolationPrinciple {


    public static class Demo {
        public static int example = 1;
    }

    public static class MyClassLoader extends ClassLoader {

        private String classPath;

        public MyClassLoader(String classPath){
            this.classPath = classPath;
        }

        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if(!name.contains("java.lang")){
                byte[] data =new byte[0];
                data = load(name);
                return defineClass(name,data,0,data.length);
            }
            return super.loadClass(name);
        }

        private byte[] load(String name){
            name =name.replaceAll("\\.","/");
            String dir = classPath+"/"+name+".calss";
            try {
                FileInputStream io = new FileInputStream(dir);
                int len = io.available();
                byte[] data = new byte[len];
                io.read(data);
                io.close();
                return data;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            return super.findClass(name);
        }
    }


}
